package com.huan.seata.service.impl;

import com.huan.seata.service.AccountService;
import com.huan.seata.service.BusinessService;
import com.huan.seata.service.OrderService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author huan.fu 2021/9/27 - 下午2:35
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class BusinessServiceImpl implements BusinessService {
    
    private final OrderService orderService;
    private final AccountService accountService;
    
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void createAccountOrder(Integer accountId, Long amount, boolean hasException) {
        System.out.println("xid:" + RootContext.getXID());
        // 1、远程扣减账户余额
        accountService.debit(accountId, amount);
        log.info("账户库扣减库成功");
        
        // 2、下订单
        orderService.createOrder(accountId, amount);
        log.info("订单库下订单成功");
        
        if (hasException) {
            throw new RuntimeException("发生了异常，分布式事物需要回滚");
        }
    }
}
